package cn.com.czpb.client.module;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import cn.com.czpb.client.R;
import cn.com.czpb.client.model.version.VersionBean;
import cn.com.czpb.client.model.version.VersionEntity;
import cn.com.czpb.client.module.news.dialog.PermisionDialog;
import cn.com.czpb.client.module.version.UpdateVersionListener;
import cn.com.czpb.client.module.version.VersionCheck;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.services.InitService;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;

import com.bumptech.glide.request.animation.ViewPropertyAnimation;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;

import org.litepal.tablemanager.Connector;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class WelcomeActivity extends Activity {
    @BindView(R.id.adflash_img_ad)
    ImageView adflashImgAd;
    protected SPUtil spu;//
    private String obj;
    private AnimatorSet animSetFadeout;
    private AnimatorSet animSetFadein;
    private String imgStr;

    //申请权限
    private static final int REQUEST_CODE_PERMISSION_MULTI = 100;
    private static final int REQUEST_CODE_SETTING = 300;
    // 所需的全部权限
    private static final String[] PERMISSIONS = new String[]{
//            Manifest.permission.CAMERA,//照相机权限
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入存储的权限;
            Manifest.permission.READ_PHONE_STATE,//写入存储的权限;
//            Manifest.permission.ACCESS_COARSE_LOCATION,//地址
    };

    private VersionCheck mVersionCheck;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

//        if (!this.isTaskRoot()) {
//            Intent intent = getIntent();
//            if (intent != null) {
//                String action = intent.getAction();
//                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
//                    finish();
//                    return;
//                }
//            }
//        }


        LogUtils.i("git 测试");
        ButterKnife.bind(this);
        // 检测权限
        spu = SPUtil.getInstance();
//        if (spu.getIsFirst()){
//            showPermissionDialog();
//
//        }else{
            checkPermissions1();
//        }

        Intent service = new Intent(this, InitService.class);
        service.setAction(InitService.InitAction);
        this.startService(service);

        Connector.getDatabase();
        imgStr = spu.getWelcome();
//        if (DeviceUtils.isRoot()){
//            TUtils.toast("广西云检测到手机已经root");
//        }
        //检查更新
    }
    private void showPermissionDialog() {

        final PermisionDialog permisionDialog = new PermisionDialog(
                WelcomeActivity.this, R.style.ChangeCitydialog); // 0为修改昵称 1为修改个人签名
        permisionDialog.show();
        permisionDialog.setOnClickKnowListener(new PermisionDialog.OnClickKnowListener() {
            @Override
            public void onCancelClick() {
                WelcomeActivity.this.finish();
                spu.setIsFirst(true);
            }
            @Override
            public void onNextClick() {
                spu.setIsFirst(false);
                checkPermissions1();
            }
        });
    }
    //检测更新
    private void checkUpdata() {
        Map<String, String> map = new HashMap<>();
        Factory.provideHttpService().checkUpdata()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<VersionEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        goMain();
                    }

                    @Override
                    public void onNext(VersionEntity entity) {

                        updata(entity.data);
                    }
                });
    }
    //更新
    private void updata(VersionBean bean) {
        mVersionCheck = new VersionCheck(this, bean, new UpdateVersionListener() {
            @Override
            public void onVersionChecked(boolean isNeedUpdate) {
                if (!isNeedUpdate) {
                    goMain();
                }
            }

            @Override
            public void onUpdateInfoDialogDismiss(boolean isClickDownLoadButton) {
                if (!isClickDownLoadButton) {
                    goMain();
                }
            }

            @Override
            public void onDownLoadDialogDismiss(boolean isDownLoadSuccess) {
                //没有下载完成
                if (!isDownLoadSuccess) {
                    mVersionCheck.beginCheckVersion();
                }
            }

            @Override
            public void onInstallAPK() {
                finish();
            }
        });
        mVersionCheck.beginCheckVersion();
    }

    //挑转到主页面;
    public void goMain() {
        String oldcity = spu.getCurrentLocation();
//        if("0".equals(oldcity)){
//            showCityDialog();
//        }else{
            PageCtrl.start2MainActivity(this);
            finish();
//        }
    }


    private void setImageViewAnimation() {
        LogUtils.i("setImageViewAnimation");
        int dur = 1500;
        animSetFadeout = new AnimatorSet();
        ObjectAnimator oanimFadeout = ObjectAnimator
                .ofFloat(adflashImgAd, "alpha", 1.0f, 0.0f)
                .setDuration(dur);
        oanimFadeout.setInterpolator(new AccelerateInterpolator());
        animSetFadeout.play(oanimFadeout);
        animSetFadeout.setDuration(1000);
        animSetFadeout.addListener(new Animator.AnimatorListener() {
            ViewPropertyAnimation.Animator animationObject = new ViewPropertyAnimation.Animator() {
                @Override
                public void animate(View view) {
                    view.setAlpha( 0f );

                    ObjectAnimator fadeAnim = ObjectAnimator.ofFloat( view, "alpha", 0f, 1f );
                    fadeAnim.setDuration( 1000 );
                    fadeAnim.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            checkUpdata();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    fadeAnim.start();
                }
            };
            @Override
            public void onAnimationCancel(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                LogUtils.i("imgstr-->"+imgStr);
                //将imgStr暂时置空，因为服务端静态资源不可用
//                imgStr = null;
                if (null != imgStr) {
                    String[] imglist = imgStr.split(",");
                    //为了美观暂时不用
                    String imgurl = imglist [(int) (Math.random()*imglist.length)];
                    LogUtils.i("!=imgurl-->" + imgurl);
                    if (!TextUtils.isEmpty(imgurl)) {
//                        LogUtils.i("url-->" + imgurl);
//                        if (WelcomeActivity.this!=null){
//                            Glide.with(WelcomeActivity.this).load(imgurl).skipMemoryCache(true).animate(animationObject).error(R.drawable.welcome_bg)
//                                    .into(adflashImgAd);
//                        }
                        if (WelcomeActivity.this!=null) {
                            Glide.with(WelcomeActivity.this).load(R.drawable.welcome_bg).skipMemoryCache(true).animate(animationObject)
                                    .into(adflashImgAd);
                        }
                    }
                } else {
                    if (WelcomeActivity.this!=null) {
                        Glide.with(WelcomeActivity.this).load(R.drawable.welcome_bg).skipMemoryCache(true).animate(animationObject)
                                .into(adflashImgAd);
                    }
                }
//                animSetFadein.start();
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationStart(Animator arg0) {

            }
        });
        animSetFadeout.start();
    }

    //申请权限成功
    @PermissionYes(REQUEST_CODE_PERMISSION_MULTI)
    private void getMultiYes(@NonNull List<String> grantedPermissions) {

        setImageViewAnimation();
    }

    //申请权限失败
    @PermissionNo(REQUEST_CODE_PERMISSION_MULTI)
    private void getMultiNo(@NonNull List<String> deniedPermissions) {

        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
//            AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING).show();

            // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
                    .setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权！")
                    .setPositiveButton("好，去设置")
                    .show();

////            第三种：自定义dialog样式。
//            SettingService settingService = AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
////            你的dialog点击了确定调用：
//            settingService.execute();
////            你的dialog点击了取消调用：
//            settingService.cancel();
        }
    }

    private void checkPermissions1() {
        RxPermissions.getInstance(getApplicationContext())
                .request(PERMISSIONS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        LogUtils.i("granted-->"+granted);
                        if (!granted) {
//                            TUtils.toast( "缺少必要权限，应用无法启动");
                            new AlertDialog.Builder(WelcomeActivity.this).setTitle("您拒绝了我们必要的一些权限，请在权限中授权！")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            finish();
                                        }
                                    })
                                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            getAppDetailSettingIntent(WelcomeActivity.this);
                                        }
                                    })
                                    .show();
                        } else {
                            setImageViewAnimation();

                        }
                    }
                });
    }
    /**
     * 跳转到权限设置界面
     */
    private void getAppDetailSettingIntent(Context context) {

        // vivo 点击设置图标>加速白名单>我的app
        //      点击软件管理>软件管理权限>软件>我的app>信任该软件
        Intent appIntent = context.getPackageManager().getLaunchIntentForPackage("com.iqoo.secure");
        if (appIntent != null) {
            context.startActivity(appIntent);
//            floatingView = new SettingFloatingView(this, "SETTING", getApplication(), 0);
//            floatingView.createFloatingView();
            return;
        }

        // oppo 点击设置图标>应用权限管理>按应用程序管理>我的app>我信任该应用
        //      点击权限隐私>自启动管理>我的app
        appIntent = context.getPackageManager().getLaunchIntentForPackage("com.oppo.safe");
        if (appIntent != null) {
            context.startActivity(appIntent);
//            floatingView = new SettingFloatingView(this, "SETTING", getApplication(), 1);
//            floatingView.createFloatingView();
            return;
        }

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(intent);
    }



    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
